package com.masterclient.app.modules.purchase;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.alibaba.android.arouter.launcher.ARouter;
import com.eoner.baselib.utils.notify.RxBus;
import com.eoner.baselib.utils.toast.ToastUtil;
import com.eoner.baselibrary.bean.goods.ProductSpecificationData;
import com.eoner.baselibrary.bean.order.ConfirmOrderData;
import com.eoner.baselibrary.bean.purchase.PurchaseProductData;
import com.eoner.common.config.Config;
import com.eoner.managerlibrary.router.AroutePath;
import com.masterclient.app.BaseFragment;
import com.masterclient.app.R;
import com.masterclient.app.base.ProgressLoginDialog;
import com.masterclient.app.modules.purchase.adapter.PurchaseProductAdapter;
import com.masterclient.app.modules.purchase.contract.PurchaseProductContract;
import com.masterclient.app.modules.purchase.contract.PurchaseProductPresenter;
import com.masterclient.app.modules.purchase.widget.PurchaseSkuDialog;
import com.masterclient.app.modules.purchase.widget.SelectGoodsDialog;
import com.eoner.uikit.header.MyRefreshHead;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONException;
import org.json.JSONObject;
import java.util.Map;
import butterknife.BindView;
import io.reactivex.functions.Consumer;

/**
 * 作者：sean
 * 创建时间：2017/7/27 10:09
 * 功能说明：
 */
public class PurchaseProductFragment extends BaseFragment<PurchaseProductPresenter> implements PurchaseProductContract.View {

    public static String GIF_PRODUCT = "gif_product";//礼包商品
    public static String NORMAL_PRODUCT = "normal_product";//零售商品

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.swipeLayout)
    SmartRefreshLayout swipeLayout;
    @BindView(R.id.ll_grand_total)
    LinearLayout viewGrandTotal;
    @BindView(R.id.tv_grand_total_text_front)
    TextView tvGrandTotalTextFront;
    @BindView(R.id.tv_grand_total_num)
    TextView tvGrandTotalNum;
    @BindView(R.id.tv_grand_total_text_after)
    TextView tvGrandTotalTextAfter;

    private String type;
    private String productsJson;
    private PurchaseProductAdapter purchaseProductAdapter;
    private ProgressLoginDialog progressDialog;
    private OnCartNumChangeListener onCartNumChangeListener;
    private RxBus rxBus;

    public static PurchaseProductFragment getInstance(String type) {
        PurchaseProductFragment purchaseProductFragment = new PurchaseProductFragment();
        Bundle bundle = new Bundle();
        bundle.putString("type", type);
        purchaseProductFragment.setArguments(bundle);
        return purchaseProductFragment;
    }

    public void setCartNumChangeListener(OnCartNumChangeListener onCartNumChangeListener){
        this.onCartNumChangeListener = onCartNumChangeListener;
    }

    @Override
    protected View getRootView(LayoutInflater inflater) {
        return inflater.inflate(R.layout.fragment_purchase_product, null);
    }

    @Override
    protected void initOnlyOnce() {
        super.initOnlyOnce();

        rxBus = RxBus.$();
        type = (String) getArguments().get("type");

        swipeLayout.setRefreshHeader(new MyRefreshHead(getActivity()));
        swipeLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                onCartNumChangeListener.refreshList(type);
            }
        });

        rxBus.OnEvent(rxBus.register(Config.PURCHASE_SUBMIT_ORDER), new Consumer<Object>() {
            @Override
            public void accept(@io.reactivex.annotations.NonNull Object o) throws Exception {
                if (skuDialog != null) skuDialog.dismiss();
                if (goodsDialog != null) goodsDialog.dismiss();
            }
        });

        purchaseProductAdapter = new PurchaseProductAdapter();
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        purchaseProductAdapter.bindToRecyclerView(recyclerView);
        recyclerView.setNestedScrollingEnabled(false);

        initListener();
    }

    private void initListener(){
        purchaseProductAdapter.setOnItemClickListener((adapter, view, position) ->
                ARouter.getInstance().build(AroutePath.PURCHASE_PRODUCT_DETAIL_ACTIVITY)
                .withString("product_id",purchaseProductAdapter.getData().get(position).getProduct_id())
                .navigation());

        purchaseProductAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            showProgress();
            mPresenter.getProductSpecification(purchaseProductAdapter.getData().get(position).getProduct_id());
        });
    }

    public void refreshData(PurchaseProductData data){
        if (GIF_PRODUCT.equals(type)){
            //礼包商品
            if (data.getGift_products() == null || data.getGift_products().size()<=0){

            }else {
                if (!TextUtils.isEmpty(data.getGrand_text_front())){
                    viewGrandTotal.setVisibility(View.GONE);
                    tvGrandTotalTextFront.setText(String.format("%s ", data.getGrand_text_front()));
                    tvGrandTotalNum.setText(data.getGrand_total_num());
                    tvGrandTotalTextAfter.setText(String.format(" %s", data.getGrand_text_after()));
                }else {
                    viewGrandTotal.setVisibility(View.GONE);
                }
                purchaseProductAdapter.setNewData(data.getGift_products());
            }
        }else {
            //零售商品
            if (data.getNormal_products() == null || data.getNormal_products().size()<=0){

            }else {
                viewGrandTotal.setVisibility(View.GONE);
                purchaseProductAdapter.setNewData(data.getNormal_products());
            }
        }
    }

    public void finishRefresh(){
        if (swipeLayout != null) {
            swipeLayout.finishRefresh();
        }
    }

    private void showProgress(){
        if (progressDialog == null){
            progressDialog = new ProgressLoginDialog(getActivity());
        }
        progressDialog.show();
        progressDialog.setDesc("");
    }

    private void dismissProgress(){
        if (progressDialog != null){
            progressDialog.dismiss();
        }
    }

    private String getProductsStr(String product_id, String num) {
        JSONObject productsStr = new JSONObject();
        try {
            productsStr.put(product_id, num);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return productsStr.toString();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void showData(PurchaseProductData data) {

    }

    @Override
    public void showFailure(int type, String msg) {
        ToastUtil.showToast(msg);
        dismissProgress();
    }

    private PurchaseSkuDialog skuDialog;
    private SelectGoodsDialog goodsDialog;
    @Override
    public void showSpecificationData(ProductSpecificationData specificationData) {
        dismissProgress();
        skuDialog = new PurchaseSkuDialog(getActivity(), specificationData, (dialog, type, product_id, num) -> {
            if (type == 0){
                dialog.dismiss();
                showProgress();
                mPresenter.addCart(product_id,num);
            }else if (type == 1){
                goodsDialog = new SelectGoodsDialog(getActivity(), custodyType -> {
                    showProgress();
                    productsJson = getProductsStr(product_id,num);
                    mPresenter.confirmOrder(productsJson,"2",custodyType);
                });
                goodsDialog.show();
            }
        });
        skuDialog.show();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (rxBus != null) {
            rxBus.unregister(Config.PURCHASE_SUBMIT_ORDER);
        }
    }

    @Override
    public void successAddCart(Map<String, String> map) {
        dismissProgress();
        String num = map.get("cart_num");
        onCartNumChangeListener.setCartNum(TextUtils.isEmpty(num)?0:Long.parseLong(num));
        ToastUtil.showToast("加入采购清单成功");
    }

    @Override
    public void confirmOrderSuccess(ConfirmOrderData data, String isCustody) {
        dismissProgress();
        ARouter.getInstance().build(AroutePath.ORDER_SUBMIT_ACTIVITY).withString("buy_type", "2").
                withString("buy_product", productsJson).withString("saleType", "4")
                .withString("is_custody", isCustody)
                .withSerializable("confirm_order_data", data).navigation();
    }

    interface OnCartNumChangeListener{
        void setCartNum(long num);
        void refreshList(String type);
    }
}
